<template>
  <div>
    
      <el-form
        ref="formItem"
        :rules="formItemRule"
        :model="formItem"
        label-width="100px"
        @submit.native.prevent
      >
        <div style="display: grid;grid-template-columns: 1fr 1fr ;grid-gap: 20px;">
          <el-form-item label="服务人员id：" v-if="formItem.id">
            <el-input disabled v-model="formItem.id" placeholder></el-input>
          </el-form-item>
          <el-form-item label="称呼：" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入称呼"></el-input>
          </el-form-item>
          <el-form-item label="姓名：" prop="name">
            <el-input v-model.trim="formItem.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="性别：" prop="sex">
            <el-radio-group v-model="formItem.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="联系电话：" prop="phone">
            <el-input v-model="formItem.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="提醒电话：" prop="remind_mobile">
            <el-input v-model="formItem.remindMobile" placeholder="请输入提醒电话"></el-input>
          </el-form-item>
          <el-form-item label="出生年月日：" prop="birthday">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              v-model="formItem.birthday"
              placeholder="请选择出生年月日"
              format="yyyy-MM-dd"
              @change="formItem.birthday = $event"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="所属城市：" prop="cityId">
            <el-select v-model="formItem.cityId" clearable filterable>
              <el-option
                v-for="(item, index) in cityInfo"
                :key="index"
                :value="item.id"
                :label="item.cityName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属门店：" prop="companyId">
            <el-select v-model="formItem.companyId" filterable clearable>
              <el-option
                v-for="item in company_list"
                :value="item.id"
                :key="item.id"
                :label="item.title"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row style="grid-column: 1/-1;">
            <el-col :span="12">
              <el-form-item label="登录帐号：" prop="loginName" style="grid-column: 1/-1;">
                <el-input v-model="formItem.loginName" placeholder="请输入登录帐号" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="登录密码：" prop="pwd" style="grid-column: 1/-1;">
                <el-input v-model="formItem.pwd" placeholder="请输入登录密码，为空则不修改" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="个人履历：" prop="resume" style="grid-column: 1/-1;">
            <el-input
              :autosize="{minRows:3,maxRows:3}"
              type="textarea"
              v-model="formItem.resume"
              placeholder="请输入个人履历"
              style="width: 100%;resize:none"
            ></el-input>
          </el-form-item>
          <el-form-item label="从业时间：" prop="workTime">
            <el-date-picker
              type="date"
              v-model="formItem.workTime"
              value-format="yyyy-MM-dd"
              placeholder="请选择从业时间"
              format="yyyy-MM-dd"
              @change="formItem.workTime = $event"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="上班时间：">
            <el-time-picker
              v-model="formItem.startTime"
              placeholder="请选择上班开始时间"
              value-format="HH:mm"
              format="HH:mm"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="下班时间：">
            <el-time-picker
              v-model="formItem.endTime"
              placeholder="请选择上班结束时间"
              value-format="HH:mm"
              format="HH:mm"
            ></el-time-picker>
          </el-form-item>
          <el-row style="grid-column: 1 / -1;">
            <el-col :span="16">
              <el-form-item label="上班日期：" prop="weekStr" style="grid-column: 1 / -1;">
                <el-checkbox-group v-model="formItem.weekStr" @change="weekChange">
                  <el-checkbox label="1">星期一</el-checkbox>
                  <el-checkbox label="2">星期二</el-checkbox>
                  <el-checkbox label="3">星期三</el-checkbox>
                  <el-checkbox label="4">星期四</el-checkbox>
                  <el-checkbox label="5">星期五</el-checkbox>
                  <el-checkbox label="6">星期六</el-checkbox>
                  <el-checkbox label="7">星期天</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="接单状态" style="grid-column: 1 / -1;">
                <el-radio-group v-model="formItem.status">
                  <el-radio :label="0">不接单</el-radio>
                  <el-radio :label="1">接单</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="经纬度：" prop="latlng">
            <el-tooltip content="请点击查找位置选择位置">
              <el-input enter-button="查找位置" v-model="formItem.latlng" placeholder="请查找位置" >
                <el-button slot="append"  type="primary" icon="el-icon-search" @click="onSearch"></el-button>
              </el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="工作地点：" prop="place">
            <el-input v-model="formItem.place" placeholder="暂未选择工作地点" disabled></el-input>
          </el-form-item>
          <el-row style="grid-column: 1 / -1;">
            <el-col :span="8">
              <el-form-item label="头像：" prop="image">
                <div class="picBox" @click="modalPicTap(false,'thumb')">
                  <div class="pictrue" v-if="formItem.thumb">
                    <img v-lazy="formItem.thumb" />
                  </div>
                  <div class="upLoad acea-row row-center-wrapper" v-else>
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
                <div style="color: #808080">推荐上传尺寸 72*72</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证正面：" prop="idcardA">
                <div class="picBox" @click="modalPicTap(false,'idcardA')">
                  <div class="pictrue" v-if="formItem.idcardA">
                    <img v-lazy="formItem.idcardA" />
                  </div>
                  <div class="upLoad acea-row row-center-wrapper" v-else>
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证背面" prop="idcardB">
                <div class="picBox" @click="modalPicTap(false,'idcardB')">
                  <div class="pictrue" v-if="formItem.idcardB">
                    <img v-lazy="formItem.idcardB" />
                  </div>
                  <div class="upLoad acea-row row-center-wrapper" v-else>
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="grid-column: 1 / -1;">
            <el-col :span="8">
              <el-form-item label="健康证" prop="healthPic">
                <div class="picBox" @click="modalPicTap(false,'healthPic')">
                  <div class="pictrue" v-if="formItem.healthPic">
                    <img v-lazy="formItem.healthPic" />
                  </div>
                  <div class="upLoad acea-row row-center-wrapper" v-else>
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="grid-column: 1 / -1;">
            <el-col :span="12">
              <el-form-item label="身份证：" prop="idcardNo">
                <el-input
                  placeholder="请输入身份证号"
                  element-id="sort"
                  v-model="formItem.idcardNo"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="接单范围(km)：" prop="serviceRadius">
            <el-input-number
              placeholder="请输入接单范围"
              element-id="sort"
              :precision="0"
              :min="0"
              v-model="formItem.serviceRadius"
              style="width: 100%;"
            />
          </el-form-item>

          <el-form-item label="信用分：" prop="serviceScore">
            <el-input-number
              placeholder="请输入信用分"
              element-id="sort"
              :precision="0"
              :min="0"
              :max="100"
              v-model="formItem.serviceScore"
              style="width: 100%;"
            />
          </el-form-item>

          <el-form-item label="酬劳比例：" prop="feeRate">
            <el-input-number
              placeholder="请输入酬劳比例"
              element-id="sort"
              :precision="0"
              :min="0"
              :max="100"
              v-model="formItem.feeRate"
              style="width: 100%;"
            />
            <div style="color: gray">全额为100</div>
          </el-form-item>

          <el-form-item label="排序：">
            <el-input-number
              placeholder="请输入排序"
              element-id="sort"
              :precision="0"
              v-model="formItem.sort"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="close()">取消</el-button>
            <el-button class="btn-save" type="primary" @click="submit()">保存</el-button>
          </el-form-item>
        </div>
      </el-form>
        <!-- 地图弹框 -->

      <el-dialog :visible.sync="modalMap" foothide title="请选择地址" append-to-body>
        <iframe id="mapPage" width="100%" height="1000px" frameborder="0" v-bind:src="keyUrl"></iframe>
      </el-dialog>
  </div>
</template>

<script>
import { cityList, saveStaffApi, getCompanyListApi, getStaffFromDataApi } from '@/api/base';
// import { keyApi } from '@/api/setting';
// import customerInfo from '@/components/customerInfo';

export default {
  name: 'staffEdit',
  components: {
    // customerInfo,
  },
  props: {
    id: {
      default: 0,
    },
    modals:false
  },
  watch: {},

  data() {
    var checkTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择从业时间'));
      }
      callback();
    };

    var checkBirth = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择出生日期'));
      }
      callback();
    };
    var checkResume = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入个人描述'));
      }
      callback();
    };
    var checkSex = (rule, value, callback) => {
      if (value === 0) {
        return callback(new Error('请选择性别'));
      }
      callback();
    };
    var checkCityId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择城市'));
      }
      callback();
    };
    var checkWeekStr = (rule, value, callback) => {
      if (value.length == 0) {
        return callback(new Error('请选择工作时间（星期）'));
      }
      callback();
    };
    var checkScore = (rule, value, callback) => {
      if (value == 0) {
        return callback(new Error('请输入信用分数'));
      }
      callback();
    };
    return {
      isChoice: '单选',
      modalCompany: false,
      modalPic: false,
      labelShow: false,
      customerShow: false,
      orderStatus: 0,
      total_num: 0,
      splitSwitch: true,
      modalMap: false,
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },
      keyUrl: '',
      formItem: {
        companyId: '',
        cityId: '',
        title: '',
        name: '',
        loginName: '',
        pwd: '',
        thumb: '',
        phone: '',
        sex: 1,
        sort: 0,
        status: 0,
        birthday: '',
        workTime: '',
        resume: '',
        startTime: '',
        endTime: '',
        weekStr: [],
        serviceScore: 60,
        serviceRadius: 0,
        // imgs: [],
        feeRate: 100,
        place: '',
        latitude: '',
        longitude: '',
        latlng: '',
        image: '',
        remindMobile: '', //提醒电话
        idcardA: '',
        idcardB: '',
        healthPic: '',
        idcardNo: '',
      },
      images: [],
      cityInfo: [],
      dataLabel: [],
      staff_id: 0,
      company_list: [],
      formItemRule: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        cityId: [
          {
            required: true,
            validator: checkCityId,
            type: String,
            trigger: 'change',
          },
        ],
        title: [
          {
            required: true,
            message: '请输入称呼',
            trigger: 'blur',
          },
        ],
        loginName: [
          {
            required: true,
            message: '请输入登录名',
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
        ],
        workTime: [
          {
            required: true,
            validator: checkTime,
            trigger: 'change',
          },
        ],
        birthday: [
          {
            required: true,
            validator: checkBirth,
            trigger: 'change',
          },
        ],
        resume: [
          {
            required: true,
            validator: checkResume,
            type: String,
            trigger: 'blur',
          },
        ],
        weekStr: [
          {
            required: true,
            validator: checkWeekStr,
            type: Object,
            trigger: 'change',
          },
        ],
        serviceScore: [
          {
            required: true,
            validator: checkScore,
            type: Number,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  mounted() {
    // 把父组件在带过来的数据绑定到组件数据中
    // this.reset();
    // 判断是否有id
    if (this.id) {
      this.getStaffInfo();
    }
    this.getCompanyList();
    this.getCitys();
    window.addEventListener(
      'message',
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          window.parent.selectAdderss(loc);
        }
      },
      false,
    );
    window.selectAdderss = this.selectAdderss;
  },
  methods: {
    weekChange(e){
      console.log(e);
    },
    getStaffInfo() {
      getStaffFromDataApi({ id: this.id }).then((res) => {
        let data = res;
        Object.entries(this.formItem).forEach(([index, item]) => {
          //分割weekStr
          if (index == 'weekStr' && data.weekStr) this.formItem.weekStr = data.weekStr.split(',');
          else if(index == 'weekStr' && !data.weekStr) this.formItem.weekStr = [];
          else if (index == 'companyId') this.formItem.companyId = data.companyId > 0 ? data.companyId: '';
          else {
            this.formItem[index] = data[index];
          }
        });
        this.formItem.latlng = data.latitude + ',' + data.longitude
        this.formItem.pwd = '';
      });
    },
    getCompanyList() {
      let itemForm = {
        status: 'all',
        field_key: 'title',
      };
      getCompanyListApi(itemForm)
        .then((res) => {
          let data = res;
          this.company_list = data.list;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.err('查询不到');
        });
    },
    customer() {
      this.modalPic = true;
    },
    customerUser() {
      this.customerShow = true;
    },
    close() {
      this.$emit('submitSuccess');
    },
    //获取城市列表
    getCitys() {
      cityList({limit:999}).then((res) => {
        let data = res;
        this.cityInfo = data.list;
      });
    },
    // 人员数据提交
    submit() {
      // alert('人员数据提交');
      let data = JSON.parse(JSON.stringify(this.formItem));
      data.id = this.id
      if(data.weekStr){
        data.weekStr = (data.weekStr).join(',')
      }
      // data.weekStr = [];
      if(!data.pwd){
        delete data.pwd
      }
      this.$refs['formItem'].validate((valid) => {
        if (valid) {
          saveStaffApi(data)
            .then((res) => {
              this.$message.success('上传成功');
              Object.assign(this.$data['formItem'], this.$options.data()['formItem']);
              this.$emit('submitSuccess');
            })
            .catch((err) => {
              this.$message.error(err.msg);
            });
        }
      });
    },
    selectAdderss(data) {
      this.formItem.place = data.poiname;
      this.formItem.latitude = data.latlng.lat;
      this.formItem.longitude = data.latlng.lng;
      this.formItem.latlng = data.latlng.lat + ',' + data.latlng.lng;
      this.modalMap = false;
    },
    onSearch() {
      this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=UAXBZ-BVZCW-H26RV-YEIPR-IS4VE-Z3FIA&referer=myapp`;
      this.modalMap = true;

      // if (!this.keyUrl) {
      //   keyApi()
      //     .then(async (res) => {
      //       let keys = res.data.key;
      //       this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${keys}&referer=myapp`;
      //       this.modalMap = true;
      //     })
      //     .catch((res) => {
      //       this.$Message.error(res.msg);
      //     });
      // } else {
      //   this.modalMap = true;
      // }
    },
    //上传图片
    modalPicTap(multiple, index) {
      const _this = this;
      if (multiple) {
        this.$modalUpload(
          function (img) {
            if (!img) return;
            if (img.length > 10) return this.$message.warning('最多选择8张图片！');
            if (img.length + _this.formItem[index].length > 10) return this.$message.warning('最多选择8张图片！');
            img.map((item) => {
              _this.formItem[index].push(item.sattDir);
            });
          },
          multiple,
          'store',
        );
      } else {
        this.$modalUpload(
          function (img) {
            if (!img) return;
            _this.formItem[index] = img[0].sattDir;
          },
          multiple,
          'store',
        );
      }
    },
    // 重置
    reset() {
      this.formItem = {
        companyId: '',
        cityId: '',
        title: '',
        name: '',
        loginName: '',
        pwd: '',
        thumb: '',
        phone: '',
        sex: 1,
        sort: 0,
        status: 0,
        birthday: '',
        workTime: '',
        resume: '',
        startTime: '',
        endTime: '',
        weekStr: [],
        serviceScore: 60,
        serviceRadius: 0,
        imgs: [],
        feeRate: 100,
        place: '',
        latitude: '',
        longitude: '',
        latlng: '',
        image: '',
        // remind_uid: 0,
        remind_mobile: '', //提醒电话
        // bind_user_name: '',
        idcardA: '',
        idcardB: '',
        healthPic: '',
        idcardNo: '',
      };
    },
  },
};
</script>

<style lang="stylus" scoped>
.labelInput {
  border: 1px solid #dcdee2;
  width: 400px;
  padding: 0 8px;
  border-radius: 5px;
  min-height: 30px;
  cursor: pointer;

  .span {
    color: #c5c8ce;
  }

  .iconxiayi {
    font-size: 12px;
  }
}

.ivu-form-item {
  margin-bottom: 10px;
}

.form-sty {
  width: 400px !important;
}

.addfont {
  display: inline-block;
  font-size: 13px;
  font-weight: 400;
  color: #1890FF;
  margin-left: 14px;
  cursor: pointer;
  margin-left: 10px;
}

.ivu-icon-ios-arrow-down {
  font-size: 14px;
}

.item {
  margin-top: 20px;
}

.tip {
  color: #bbb;
}

.picBox {
  display: inline-block;
  cursor: pointer;

  .upLoad {
    width: 58px;
    height: 58px;
    line-height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
  }

  .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 10px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .iconfont {
    color: #898989;
  }
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;

  img {
    width: 100%;
    height: 100%;
  }
}

.footer {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: end;

  .btn-save {
    margin-left: 10px;
  }
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}

.upLoad {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}
</style>